#!/bin/sh

K8S_GKE_NAME="${K8S_GKE_NAME:-stackgres-e2e}"
K8S_VERSION="${K8S_VERSION:-1.14.10-gke.50}"
if [ "$K8S_VERSION" = "$DEFAULT_K8S_VERSION" ]
then
  >&2 echo "Warning: using kubernetes version 1.13.11 since e2e default $DEFAULT_K8S_VERSION is not available for gke"
  K8S_VERSION=1.14.10-gke.50
fi
K8S_GKE_REGION="${K8S_GKE_REGION:-us-west1}"
K8S_GKE_NODE_LOCATIONS="${K8S_GKE_NODE_LOCATIONS:-us-west1-a}"
K8S_GKE_MACHINE_TYPE="${K8S_GKE_MACHINE_TYPE:-n1-standard-1}"
K8S_GKE_DISK_SIZE="${K8S_GKE_DISK_SIZE:-20}"
K8S_GKE_NODES="${K8S_GKE_NODES:-1}"
K8S_GKE_PROJECT="${K8S_GKE_PROJECT:-default}"
K8S_GKE_OPTS="$K8S_GKE_OPTS"
K8S_GKE_SERVICEACCOUNT="${K8S_GKE_SERVICEACCOUNT:-stackgres-e2e}"
K8S_GKE_ACCOUNT_EMAIL="$K8S_GKE_SERVICEACCOUNT@$K8S_GKE_PROJECT.iam.gserviceaccount.com"
K8S_GKE_ACCOUNT_MEMBER="serviceAccount:$K8S_GKE_ACCOUNT_EMAIL"

export E2E_USE_INTERMIDIATE_PRIVATE_REPO="${E2E_USE_INTERMIDIATE_PRIVATE_REPO:-true}"
export E2E_OPERATOR_PULL_POLICY=Always

export K8S_GKE_NAME K8S_VERSION K8S_GKE_REGION K8S_GKE_NODE_LOCATIONS K8S_GKE_MACHINE_TYPE K8S_GKE_DISK_SIZE K8S_GKE_PROJECT K8S_GKE_OPTS USE_INTERMIDIATE_PRIVATE_REPO

get_k8s_env_version() {
  echo "gcloud version $(gcloud version | tr '\n' ' ')"
  echo
}

reuse_k8s() {
  if ! gcloud -q beta container --project "$K8S_GKE_PROJECT" clusters describe "$K8S_GKE_NAME" --region "$K8S_GKE_REGION" 2>&1 \
    | grep -q "status: RUNNING"
  then
    echo "Can not reuse gke environment $K8S_GKE_NAME"
    exit 1
  fi

  echo "Reusing gke environment $K8S_GKE_NAME"

  gcloud -q beta container --project "$K8S_GKE_PROJECT" clusters get-credentials "$K8S_GKE_NAME" --region "$K8S_GKE_REGION"
}

reset_k8s() {
  echo "Setting up gke environment $K8S_GKE_NAME..."

  delete_k8s
  gcloud -q beta container --project "$K8S_GKE_PROJECT" clusters create "$K8S_GKE_NAME" \
    --region "$K8S_GKE_REGION" \
    --node-locations "$K8S_GKE_NODE_LOCATIONS" \
    --machine-type "$K8S_GKE_MACHINE_TYPE" \
    --disk-size "$K8S_GKE_DISK_SIZE" \
    --num-nodes "$K8S_GKE_NODES" \
    --cluster-version "$K8S_VERSION" \
    --no-enable-autoupgrade \
    --workload-pool="$K8S_GKE_PROJECT.svc.id.goog" \
    $K8S_GKE_OPTS

  if [ ! -f "$TARGET_PATH/gke-service-account.json" ]
  then
    gcloud --project "$K8S_GKE_PROJECT" iam service-accounts create "$K8S_GKE_SERVICEACCOUNT" || true

    gcloud projects add-iam-policy-binding "$K8S_GKE_PROJECT" --member="$K8S_GKE_ACCOUNT_MEMBER" --role=roles/storage.admin || true

    gcloud iam service-accounts keys create "$TARGET_PATH/gke-service-account.json" --iam-account "$K8S_GKE_ACCOUNT_EMAIL"
  fi

  echo "...done"
}

delete_k8s() {
  echo "Deleting gke environment $K8S_GKE_NAME..."

  if gcloud -q beta container --project "$K8S_GKE_PROJECT" clusters describe "$K8S_GKE_NAME" --region "$K8S_GKE_REGION" 2>&1 \
    | grep -q "status: RUNNING"
  then
    gcloud -q beta container --project "$K8S_GKE_PROJECT" clusters delete "$K8S_GKE_NAME" --region "$K8S_GKE_REGION" || true
  fi
  gcloud -q compute disks list --project "$K8S_GKE_PROJECT" --filter "zone:($K8S_GKE_REGION)" \
    | tail -n+2 | sed 's/ \+/|/g' | cut -d '|' -f 1-2 \
    | grep '^gke-'"$K8S_GKE_NAME"'-[0-9a-f]\{4\}-pvc-[0-9a-f]\{8\}-[0-9a-f]\{4\}-[0-9a-f]\{4\}-[0-9a-f]\{4\}-[0-9a-f]\{12\}|' \
    | xargs_shell % -ec "gcloud -q compute disks delete --project '$K8S_GKE_PROJECT' --zone \"\$(echo '%' | cut -d '|' -f 2)\" \"\$(echo '%' | cut -d '|' -f 1)\""

  echo "...done"
}

load_image_k8s() {
  echo "Cannot load images directly to k8s in a gke environment."
  exit 1
}

excluded_namespaces() {
  echo "default"
  echo "kube-node-lease"
  echo "kube-public"
  echo "kube-system"
}

excluded_validatingwebhookconfigurations() {
  true
}

excluded_mutatingwebhookconfigurations() {
  echo "pod-ready.config.common-webhooks.networking.gke.io"
}

excluded_customresourcedefinitions() {
  echo "backendconfigs.cloud.google.com"
  echo "capacityrequests.internal.autoscaling.k8s.io"
  echo "frontendconfigs.networking.gke.io"
  echo "managedcertificates.networking.gke.io"
  echo "servicenetworkendpointgroups.networking.gke.io"
  echo "updateinfos.nodemanagement.gke.io"
  echo "volumesnapshotclasses.snapshot.storage.k8s.io"
  echo "volumesnapshotcontents.snapshot.storage.k8s.io"
  echo "volumesnapshots.snapshot.storage.k8s.io"
}

excluded_podsecuritypolicies() {
  echo "gce.gke-metrics-agent"
}

excluded_clusterroles() {
  echo "admin"
  echo "ca-cr-actor"
  echo "cloud-provider"
  echo "cluster-admin"
  echo "cluster-autoscaler"
  echo "edit"
  echo "external-metrics-reader"
  echo "gce:beta:kubelet-certificate-bootstrap"
  echo "gce:beta:kubelet-certificate-rotation"
  echo "gce:cloud-provider"
  echo "gce:gke-metadata-server-reader"
  echo "gke-metrics-agent"
  echo "kubelet-api-admin"
  echo "netd"
  echo "read-updateinfo"
  echo "snapshot-controller-runner"
  echo "stackdriver:metadata-agent"
  echo "system:aggregate-to-admin"
  echo "system:aggregate-to-edit"
  echo "system:aggregate-to-view"
  echo "system:auth-delegator"
  echo "system:basic-user"
  echo "system:certificates.k8s.io:certificatesigningrequests:nodeclient"
  echo "system:certificates.k8s.io:certificatesigningrequests:selfnodeclient"
  echo "system:clustermetrics"
  echo "system:controller:attachdetach-controller"
  echo "system:controller:certificate-controller"
  echo "system:controller:clusterrole-aggregation-controller"
  echo "system:controller:cronjob-controller"
  echo "system:controller:daemon-set-controller"
  echo "system:controller:deployment-controller"
  echo "system:controller:disruption-controller"
  echo "system:controller:endpoint-controller"
  echo "system:controller:expand-controller"
  echo "system:controller:generic-garbage-collector"
  echo "system:controller:glbc"
  echo "system:controller:horizontal-pod-autoscaler"
  echo "system:controller:job-controller"
  echo "system:controller:namespace-controller"
  echo "system:controller:node-controller"
  echo "system:controller:persistent-volume-binder"
  echo "system:controller:pod-garbage-collector"
  echo "system:controller:pv-protection-controller"
  echo "system:controller:pvc-protection-controller"
  echo "system:controller:replicaset-controller"
  echo "system:controller:replication-controller"
  echo "system:controller:resourcequota-controller"
  echo "system:controller:route-controller"
  echo "system:controller:service-account-controller"
  echo "system:controller:service-controller"
  echo "system:controller:statefulset-controller"
  echo "system:controller:ttl-controller"
  echo "system:discovery"
  echo "system:gcp-controller-manager"
  echo "system:gke-common-webhooks"
  echo "system:gke-hpa-service-reader"
  echo "system:gke-master-healthcheck"
  echo "system:gke-master-resourcequota"
  echo "system:gke-uas-adapter"
  echo "system:gke-uas-collection-reader"
  echo "system:gke-uas-metrics-reader"
  echo "system:glbc-status"
  echo "system:heapster"
  echo "system:kube-aggregator"
  echo "system:kube-controller-manager"
  echo "system:kube-dns"
  echo "system:kube-dns-autoscaler"
  echo "system:kube-scheduler"
  echo "system:kubelet-api-admin"
  echo "system:kubestore-collector"
  echo "system:managed-certificate-controller"
  echo "system:master-monitoring-role"
  echo "system:metrics-server"
  echo "system:node"
  echo "system:node-bootstrapper"
  echo "system:node-problem-detector"
  echo "system:node-proxier"
  echo "system:persistent-volume-provisioner"
  echo "system:public-info-viewer"
  echo "system:resource-tracker"
  echo "system:slo-monitor"
  echo "system:volume-scheduler"
  echo "view"
}

excluded_clusterrolebindings() {
  echo "ca-cr"
  echo "cluster-admin"
  echo "cluster-autoscaler"
  echo "cluster-autoscaler-updateinfo"
  echo "event-exporter-rb"
  echo "gce:beta:kubelet-certificate-bootstrap"
  echo "gce:beta:kubelet-certificate-rotation"
  echo "gce:cloud-provider"
  echo "gce:gke-metadata-server-reader"
  echo "gke-metrics-agent"
  echo "kube-apiserver-kubelet-api-admin"
  echo "kubelet-bootstrap"
  echo "kubelet-bootstrap-certificate-bootstrap"
  echo "kubelet-bootstrap-node-bootstrapper"
  echo "kubelet-cluster-admin"
  echo "kubelet-user-npd-binding"
  echo "master-monitoring-role-binding"
  echo "metrics-server:system:auth-delegator"
  echo "netd"
  echo "npd-binding"
  echo "snapshot-controller-role"
  echo "stackdriver:metadata-agent"
  echo "system:basic-user"
  echo "system:clustermetrics"
  echo "system:controller:attachdetach-controller"
  echo "system:controller:certificate-controller"
  echo "system:controller:clusterrole-aggregation-controller"
  echo "system:controller:cronjob-controller"
  echo "system:controller:daemon-set-controller"
  echo "system:controller:deployment-controller"
  echo "system:controller:disruption-controller"
  echo "system:controller:endpoint-controller"
  echo "system:controller:expand-controller"
  echo "system:controller:generic-garbage-collector"
  echo "system:controller:glbc"
  echo "system:controller:horizontal-pod-autoscaler"
  echo "system:controller:job-controller"
  echo "system:controller:namespace-controller"
  echo "system:controller:node-controller"
  echo "system:controller:persistent-volume-binder"
  echo "system:controller:pod-garbage-collector"
  echo "system:controller:pv-protection-controller"
  echo "system:controller:pvc-protection-controller"
  echo "system:controller:replicaset-controller"
  echo "system:controller:replication-controller"
  echo "system:controller:resourcequota-controller"
  echo "system:controller:route-controller"
  echo "system:controller:service-account-controller"
  echo "system:controller:service-controller"
  echo "system:controller:statefulset-controller"
  echo "system:controller:ttl-controller"
  echo "system:discovery"
  echo "system:gcp-controller-manager"
  echo "system:gke-common-webhooks"
  echo "system:gke-hpa-service-reader"
  echo "system:gke-master-healthcheck"
  echo "system:gke-master-resourcequota"
  echo "system:gke-uas-adapter"
  echo "system:gke-uas-collection-reader"
  echo "system:gke-uas-hpa-controller"
  echo "system:gke-uas-metrics-reader"
  echo "system:glbc-status"
  echo "system:kube-controller-manager"
  echo "system:kube-dns"
  echo "system:kube-dns-autoscaler"
  echo "system:kube-proxy"
  echo "system:kube-scheduler"
  echo "system:kubestore-collector"
  echo "system:managed-certificate-controller"
  echo "system:metrics-server"
  echo "system:node"
  echo "system:node-proxier"
  echo "system:public-info-viewer"
  echo "system:resource-tracker"
  echo "system:slo-monitor"
  echo "system:volume-scheduler"
  echo "uas-hpa-external-metrics-reader"
}

get_k8s_versions() {
  cat << EOF
1.18.12-gke.1205
1.17.14-gke.1600
1.16.13-gke.1
1.16.9-gke.6
1.16.9-gke.2
1.16.8-gke.15
1.15.12-gke.3
1.15.12-gke.2
1.15.11-gke.17
1.15.11-gke.15
1.15.9-gke.24
1.14.10-gke.42
1.14.10-gke.41
1.14.10-gke.40
1.14.10-gke.37
1.14.10-gke.36
EOF
}
